package servlet;

import bean.Record_Bean;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;

@WebServlet(name = "Servlet", urlPatterns = "/Servlet")
public class Servlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException{
        super.init();
    }
    public void service(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        PrintWriter out=response.getWriter();
        request.setCharacterEncoding("utf-8");
        ResultSet rs;
        String search=request.getParameter("search");
        System.out.println(search);
        if (search==null||search.equals(""))
            search="成都";
        HttpSession session=request.getSession(true);
        Connection conn=null;
        Record_Bean dataBean=null;
            try {
                dataBean=(Record_Bean)session.getAttribute("dataBean");
                if (dataBean==null){
                    dataBean=new Record_Bean();
                    session.setAttribute("dataBean",dataBean);
                }
            }catch (Exception e){}

            try {
                String driver="org.mariadb.jdbc.Driver";
                String url="jdbc:mariadb://localhost:3306/hotel-management-system";
                Class.forName(driver);
                conn= DriverManager.getConnection(url,"root","123456");
            } catch (ClassNotFoundException | SQLException e) {
                e.printStackTrace();
            }

            try {
                Statement sql=conn.createStatement();
                String find="select * from hotels where HotelAddress like '%"+search+"%'";
                ResultSet hn=sql.executeQuery(find);
                ArrayList <String>hotelNames= dataBean.getHotelName();
                ArrayList<String> hotelAddresses=dataBean.getHotelAddress();
                ArrayList<String> hotelID=dataBean.getHotelID();
                while (hn.next()){
                    hotelNames.add(hn.getString("HotelName"));
                    hotelAddresses.add(hn.getString("HotelAddress"));
                    hotelID.add(hn.getString("HotelID"));
                }
                conn.close();
                response.sendRedirect("result.jsp");

            }catch (Exception e){
                response.getWriter().print(""+e);
            }
            finally {
                try {
                    conn.close();
                }catch (Exception e){
                    out.print(e);

                }
            }



    }
}
